const app = new getApp();
var time = require("../../../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    default_img: {},
    order_id: 0,
    info: {
      order: {
        buyer_invoice_info: '',
      },
      order_pickup: ''
    },
    operationFlag: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;

    if (options.order_id) {
      that.setData({
        order_id: options.order_id
      })

    } else {
      app.showBox(that, '无法获取订单信息');
      wx.navigateBack({
        delta: 1,
      })
      return false;
    }
    app.webSiteInfo(that, true);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.restStatus(this, 'operationFlag');
    app.defaultImg(this, true);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 加载订单详情
   */
  loadInfo: function() {
    let that = this;
    let order_id = that.data.order_id;

    app.sendRequest({
      url: 'System.Order.orderDetail',
      data: {
        order_id: order_id
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;

        console.log(res);
        if (code == 0 && data != undefined && data != '' && data != null && data != 0) {
          let info = data;
          try {

            // 异常数据格式处理
            info.order.status_name = app.checkEmpty(info.order.status_name, '');
            info.order.order_no = app.checkEmpty(info.order.order_no, '');
            info.order.status_name = app.checkEmpty(info.order.status_name, '');
            info.order.create_time = app.checkEmpty(info.order.create_time, '');
            info.order.payment_type_name = app.checkEmpty(info.order.payment_type_name, '');
            info.order.pay_status_name = app.checkEmpty(info.order.pay_status_name, '');
            info.order.shipping_type_name = app.checkEmpty(info.order.shipping_type_name, '');

            info.order.buyer_invoice_info = app.checkEmpty(info.order.buyer_invoice_info, '');
            if (info.order.buyer_invoice_info != '') {
              info.order.buyer_invoice_info[0] = app.checkEmpty(info.order.buyer_invoice_info[0], '');
              info.order.buyer_invoice_info[1] = app.checkEmpty(info.order.buyer_invoice_info[1], '');
              info.order.buyer_invoice_info[2] = app.checkEmpty(info.order.buyer_invoice_info[2], '');
            }

            info.order_pickup = app.checkEmpty(info.order_pickup, '');
            if (info.order.buyer_invoice_info != '') {
              info.order_pickup.address = app.checkEmpty(info.order_pickup.address, '');
              info.order_pickup.picked_up_code = app.checkEmpty(info.order_pickup.picked_up_code, '');
              info.order_pickup.buyer_name = app.checkEmpty(info.order_pickup.buyer_name, '');
              info.order_pickup.buyer_mobile = app.checkEmpty(info.order_pickup.buyer_mobile, '');
            }

            // 商品图片处理
            for (let index in info.order.order_goods) {
              if (info.order.order_goods[index].picture_info != undefined) {
                let img = info.order.order_goods[index].picture_info.pic_cover_small;
                info.order.order_goods[index].picture_info.pic_cover_small = app.IMG(img);
              } else {
                info.order.order_goods[index].picture_info = {};
                info.order.order_goods[index].picture_info.pic_cover_small = '';
              }
            }

            //时间格式转化
            info.order.create_time = info.order.create_time != '' ? time.formatTime(info.order.create_time, 'Y-M-D h:m:s') : info.order.create_time;
            info.order.shipping_time = info.order.shipping_time > 0 ? time.formatTime(info.order.shipping_time, 'Y-M-D') : '工作日、双休日与节假日均可送货';
            if (info.order.is_virtual == 0) {
              info.order.address = info.order.address.replace(/&nbsp;/g, '　');
            }

            if (info.order_pickup != '') {
              info.order_pickup.address = info.order_pickup.address.replace(/&nbsp;/g, '　');
            }
          } catch (e) {
            app.showBox(that, '错误的订单信息');
            console.log(e);
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            }, 2000)
          }

          that.setData({
            info: info
          })
          // 检测拼团信息
          if (info.order.order_status == 6) {
            that.loadPintuanInfo();
          }
        }
      }
    })
  },

  /**
   * 加载拼团信息
   */
  loadPintuanInfo: function() {
    let that = this;
    let order_id = that.data.order_id;
    let goods_id = that.data.info.order.order_goods[0].goods_id;
    let group_id = that.data.info.order.tuangou_group_id;

    app.sendRequest({
      url: 'NsPintuan.Pintuan.sharePintuan',
      data: {
        order_id: order_id,
        goods_id: goods_id,
        group_id: group_id
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;

        console.log(res);
        if (code == 0) {
          let pintuan_info = data;

          if (app.checkArray(pintuan_info.tuangou_group_info.user_list)) {
            for (let index in pintuan_info.tuangou_group_info.user_list) {
              let img = pintuan_info.tuangou_group_info.user_list[index].user_headimg;
              pintuan_info.tuangou_group_info.user_list[index].user_headimg = app.IMG(img);
            }
          }

          let poor_array = [];
          for (let i = 0; i < pintuan_info.tuangou_group_info.poor_num; i++) {
            poor_array[i] = {};
          }
          pintuan_info.tuangou_group_info.poor_array = poor_array;

          let time_array = {};
          time_array.end_time = pintuan_info.tuangou_group_info.end_time;
          that.timing_pintuan(that, time_array, 0);

          that.setData({
            pintuan_info: pintuan_info
          })
        }
      }
    });
  },

  /**
   * 图片加载失败
   */
  errorImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let info = that.data.info;
    let default_img = that.data.default_img;
    let parm = {};
    let img = info.order.order_goods[index].picture_info.pic_cover_small;

    if (default_img.is_use == 1) {
      default_img = default_img.value.default_goods_img;
      if (img.indexOf(default_img) == -1) {
        let parm_key = "info.order.order_goods[" + index + "].picture_info.pic_cover_small";

        parm[parm_key] = default_img;
        that.setData(parm);
      }
    }
  },

  /**
   * 拨打电话
   */
  tell: function(e) {
    let that = this;
    let web_phone = e.currentTarget.dataset.tell;
    if (app.checkEmpty(web_phone, '') != '') {
      wx.makePhoneCall({
        phoneNumber: web_phone,
      })
    } else {
      app.showBox(that, '暂无商家电话');
    }
  },

  /**
   * 拼团计时
   */
  timing_pintuan: function(that, timer_array, index) {
    let current_time = that.data.current_time;
    let count_second = (timer_array.end_time - current_time);
    let d = {};
    let parm = '';

    //首次加载
    if (count_second > 0) {
      count_second--;
      //时间计算
      let day = Math.floor((count_second / 3600) / 24);
      let hour = Math.floor((count_second / 3600) % 24);
      let minute = Math.floor((count_second / 60) % 60);
      let second = Math.floor(count_second % 60);

      hour = hour < 10 ? '0' + hour : hour;
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;
      //赋值
      timer_array.day = day;
      timer_array.hour = hour;
      timer_array.minute = minute;
      timer_array.second = second;
      timer_array.end = 0;

      d = {};
      parm = 'timers_array[' + index + ']';
      d[parm] = timer_array;
      that.setData(d);
    } else {
      timer_array.end = 1;

      d = {};
      parm = 'timers_array[' + index + ']';
      d[parm] = timer_array;
      that.setData(d);
    }
    //开始计时
    let timer = setInterval(function() {
      if (count_second > 0) {
        count_second--;
        //时间计算
        let day = Math.floor((count_second / 3600) / 24);
        let hour = Math.floor((count_second / 3600) % 24);
        let minute = Math.floor((count_second / 60) % 60);
        let second = Math.floor(count_second % 60);

        hour = hour < 10 ? '0' + hour : hour;
        minute = minute < 10 ? '0' + minute : minute;
        second = second < 10 ? '0' + second : second;
        //赋值
        timer_array.day = day;
        timer_array.hour = hour;
        timer_array.minute = minute;
        timer_array.second = second;
        timer_array.end = 0;

        d = {};
        parm = 'timers_array[' + index + ']';
        d[parm] = timer_array;
        that.setData(d);
      } else {
        timer_array.end = 1;

        d = {};
        parm = 'timers_array[' + index + ']';
        d[parm] = timer_array;
        that.setData(d);

        clearInterval(timer);
      }
    }, 1000)
  },


  /**
   * 订单操作
   */
  operation: function(event) {
    let that = this;
    let operationFlag = that.data.operationFlag;
    let action = event.currentTarget.dataset.action;
    let order_id = event.currentTarget.dataset.id;

    if (operationFlag == 1) {
      return false;
    }
    app.clicked(that, 'operationFlag');

    switch (action) {
      case 'pay': //支付
        that.pay(order_id);
        break;
      case 'close': //订单关闭
        that.orderClose(order_id);
        break;
      case 'getdelivery': //订单收货
        that.getDelivery(order_id);
        break;
      case 'logistics': //查看物流
        that.logistics(order_id);
        break;
      case 'delete_order': //删除订单
        that.deleteOrder(order_id);
        break;
      case 'pay_presell': //预定金支付
        that.payPresell(order_id);
        break;
      case 'member_pickup': // 买家自提
        that.memberPickup(order_id);
        break;
      default:
        app.restStatus(that, 'operationFlag');
        break;
    }
  },

  /**
   * 去支付
   */
  pay: function(order_id) {
    let that = this;

    app.sendRequest({
      url: 'System.Pay.orderPay',
      data: {
        order_id: order_id,
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data != undefined && (typeof(data) == 'int' || typeof(data) == 'string')) {
            let out_trade_no = data;
            let url = '/pagesother/pages/pay/getpayvalue/getpayvalue?out_trade_no=' + out_trade_no;
            wx.navigateTo({
              url: url,
            })
          } else {
            app.showBox(that, '支付失败');
            app.restStatus(that, 'operationFlag');
          }
        } else {
          app.showBox(that, res.message);
          app.restStatus(that, 'operationFlag');
        }
      }
    });
  },

  /**
   * 关闭订单
   */
  orderClose: function(order_id) {
    let that = this;

    app.sendRequest({
      url: 'System.Order.orderClose',
      data: {
        order_id: order_id
      },
      success: function(res) {
        let code = res.data;
        if (code > 0) {
          app.showBox(that, '关闭成功');
          that.loadInfo();
        } else {
          app.showBox(that, '关闭失败');
          app.restStatus(that, 'operationFlag');
        }
      }
    })
  },

  /**
   * 确认收货
   */
  getDelivery: function(order_id) {
    let that = this;

    app.sendRequest({
      url: 'System.Order.orderTakeDelivery',
      data: {
        order_id: order_id,
      },
      success: function(res) {
        let code = res.data;
        if (code > 0) {
          app.showBox(that, '收货成功');
          that.loadInfo();
        } else {
          app.showBox(that, '收货失败');
          app.restStatus(that, 'operationFlag');
        }
      }
    });
  },

  /**
   * 查看物流
   */
  logistics: function(order_id) {
    let that = this;

    wx.navigateTo({
      url: '/pagesother/pages/order/logistics/logistics?order_id=' + order_id,
    })
  },

  /**
   * 删除订单
   */
  deleteOrder: function(order_id) {
    let that = this;

    app.sendRequest({
      url: 'System.Order.deleteOrder',
      data: {
        order_id: order_id
      },
      success: function(res) {
        let code = res.data;
        if (code > 0) {
          app.showBox(that, '订单删除成功');
          wx.navigateBack({
            delta: 1
          })
        } else {
          app.showBox(that, '订单删除失败');
          app.restStatus(that, 'operationFlag');
        }
      }
    });
  },

  /**
   * 定金支付
   */
  payPresell: function(order_id) {
    let that = this;

    app.sendRequest({
      url: 'System.Pay.orderPresellPay',
      data: {
        order_id: order_id,
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data != undefined && (typeof(data) == 'int' || typeof(data) == 'string')) {
            let out_trade_no = data;
            let url = '/pagesother/pages/pay/getpayvalue/getpayvalue?out_trade_no=' + out_trade_no;
            wx.navigateTo({
              url: url,
            })
          } else {
            app.restStatus(that, 'operationFlag');
            app.showBox(that, '支付失败');
          }
        } else {
          app.showBox(that, res.message);
          app.restStatus(that, 'operationFlag');
        }
      }
    });
  },

  /**
   * 买家自提
   */
  memberPickup: function(order_id) {
    wx.navigateTo({
      url: '/pagesother/pages/order/pickup/pickup?order_id=' + order_id,
    })
  },
})